/*
 *  Cd.cpp
 *  osnutshell
 *
 *  Created by Zachary  Heylmun on 4/17/10.
 *  Copyright 2010 University of Florida. All rights reserved.
 *
 */

#include "Cd.h"

using std::string;
using std::cout;

namespace nutshell
{

	// Default Constructor
	// changes current working directory to HOME directory
	Cd::Cd()
	{
		string home = getenv("HOME");
		if (home.empty())
			cout << "Cannot locate HOME directory." << std::endl;
		else
			chdir(home.c_str());
		current_dir = "~";
	}

	// Tilde Expansion function
	// accepts a string token, and replaces ~username
	// with the home directory of username.
	// if no username is provided, replaces ~
	// with home directory of current user.
	string Cd::tilde_expansion(string s)
	{
		// if the token is empty of doesn't start with a ~, just return it
		if (s.empty() || s[0] != '~')
			return s;
		
		// parse the user name
		string::const_iterator b = s.begin() + 1;
		string::const_iterator e = std::find( s.begin(), s.end(), '/' );
		string username( b, e );
		
		// get the home directory
		string home;
	
		// if no username was provided, get home directory of current user
		if ( username.empty() )
			home = getenv("HOME");
		else
		{
			// get home directory of username
			passwd* pw = getpwnam( username.c_str() );
			if (pw == NULL)
				return s;
			home = pw->pw_dir;
		}
	
		// replace ~username with the home directory path
		s.erase(s.begin(), std::find(s.begin(), s.end(), '/') );
		s.insert(s.begin(), home.begin(), home.end());
		return s;
	}

	// BUILT IN COMMAND FUNCTION FOR cd
	void Cd::do_command(int argc, char** argv)
	{
		// if cd with no path, change directory to user home
		if (argc == 1)
		{
			string home = getenv("HOME");
			if (home.empty())
				cout << "Cannot locate HOME directory." << std::endl;
			else if(chdir(home.c_str()) == 0)
				current_dir = "~";
			else 
				std::cout << "Cannot locate " << home << "." << std::endl;
		}
		// if cd with path, change directory to path
		else if( argc == 2)
		{
			if(chdir(argv[1]) == 0)
			{
				std::string dir = argv[1];
				if (dir[0] == '/')
					current_dir = dir;
				else 
					current_dir += dir;

			}
			else 
				std::cout << "Cannot locate " << argv[1] << "." << std::endl;
		}
		else
				std::cout << "Invalid Number of Arguments to CD Function.\n";
		
	}
	
}
